dojo.provide("lotex.io");


dojo.require("dojo.lang.declare");
dojo.require("dojo.collections.ArrayList");
dojo.require("dojo.io.*");

dojo.require("lotex.commond");
dojo.require("lotex.array");


dojo.declare("lotex.io.Reserve", null,
    function(/*Object*/ bindArgs) {
        this.bindArgs = bindArgs;

        var _urls = bindArgs.url;
        if( !dojo.lang.isArray(_urls) ) return dojo.io.bind(bindArgs);

        this.urls = lotex.array.clone(_urls);
        var self = this;

        this.idx = -1;
        this.cmd = new lotex.commond.Once();
        this._error = (typeof bindArgs.error == "function") ? bindArgs.error : null ;

        this.bindArgs.error = function() {
            d("read url [" + this.url + "] failed!, try read next reserve url in urls..");
            var next = self.cmd.exec(this.url, self, "nextRequest");
            d("next : " + next);
            if(next == null && typeof self._error == "function") {
                self._error.apply(this, arguments);
            }
        }

        this.nextRequest();
    },
{
    nextRequest: function() {
        d("call nextRequest");
        this.idx++;
        if (this.idx >= this.urls.length ) return null;
        this.bindArgs.url = this.urls[this.idx];
        return dojo.io.bind(this.bindArgs);
    }
});

lotex.io.bind = function(bindArgs) {
    var _urls = bindArgs.url;
    if(!dojo.lang.isArray(_urls)) return dojo.io.bind(bindArgs);

    if(_urls.length==2)
        bindArgs.url = (lotexConfig.online) ? _urls[0] : _urls[1];

    return new lotex.io.Reserve(bindArgs);
}

lotex.io.json = function(kwArgs) {
    // FIXME hitch bug
    kwArgs.mimetype = "text/html";
    if(typeof kwArgs.load == "function") {
        onLoad = kwArgs.load;
        onError = (typeof kwArgs.error == "function") ? kwArgs.error : function(){};
        kwArgs.load = function(type, responseText, evt) {
                try{
                    data = dj_eval("("+responseText+")");
                    onLoad(type, data, evt)
                }catch(e){
                    onError("JSONParseException");
                }
            }
    }
    lotex.io.bind(kwArgs);
}